#include "blockqueue.hpp"
#include <pthread.h>
#include <ctime>
#include <unistd.h>
#include <sys/types.h>
#include "Task.hpp"

const string mode = "+-%/";
void *consumer(void* args) {
    blockqueue<Task> * bq = static_cast<blockqueue<Task> *>(args);
    // 消费者，消费数据
    while (true) {
        // sleep(1);
        Task task;
        bq->Pop(&task);
        task.run();
        printf("consumer get result: [%d %c %d == %d](code = %d)\n", task._x, task._op, task._y, task._ret, task._code);
        if (task._code == -1) {
            cout << "error……………………………………" << endl;
            exit(-1);
        }
        // sleep(1);
    }
    return nullptr;
}

void *producer(void *args) {
    blockqueue<Task> * bq = static_cast<blockqueue<Task> *>(args); // 生产者和消费者看到了同一份资源
    // 生产者，生产数据
    while (true) {
        int x = rand() % 100 + 1;
        usleep(rand() % 123);
        int  y = rand() % 100 + 1;
        usleep(rand() % 123);
        int opindex = rand() % mode.size();
        // cout << "x == " << x << ", y == " << y << ", opindex == " << opindex << endl;

        char op = mode[opindex];
        Task task(x, y, op);

        bq->Push(task);
        // cout << "productor a data: " << data << endl;
        
    }
    return nullptr;
}

int main() {
    srand((uint16_t)time(nullptr) ^ getpid() ^ pthread_self());
    blockqueue<Task> *bq = new blockqueue<Task>();
    pthread_t c, p; // 消费者和生产者
    pthread_create(&c, nullptr, consumer, bq); // 要让两个进程看到同一个资源(阻塞队列)，所以要将队列传给函数
    pthread_create(&p, nullptr, producer, bq);

    pthread_join(c, nullptr);
    pthread_join(p, nullptr);

    return 0;
}